package com.hdu.mockService.handler;

import com.hdu.mockService.annotation.RandomEntity;
import com.hdu.mockService.factory.MockHandlerFactory;
import org.apache.commons.collections4.CollectionUtils;

import java.lang.reflect.Field;
import java.util.List;

import static com.hdu.mockService.utils.ReflectionUtils.getFieldsByTargetAnnotation;

public class EntityMockHandler implements IMockHandler {
    @Override
    public void partitionMock(Object mockObj) {
        List<Field> mockEntityFields = getFieldsByTargetAnnotation(mockObj.getClass(), RandomEntity.class);
        if (CollectionUtils.isEmpty(mockEntityFields)) {
            return;
        }
        for (Field mockEntityField : mockEntityFields) {
            Class<?> filedClass = mockEntityField.getType();
            try {
                Object mockFiledObj = filedClass.newInstance();
                MockHandlerFactory.getHandlers().forEach(handler -> {
                    handler.partitionMock(mockFiledObj);
                });
                mockEntityField.setAccessible(true);
                mockEntityField.set(mockObj, mockFiledObj);
            } catch (InstantiationException | IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
